package com.jcommander.gui;

import java.awt.Component;
import java.awt.Font;
import java.util.List;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

import com.jcommander.model.FileSystemNode;

public class TextIconComboBoxRenederer extends JLabel implements ListCellRenderer{


	private static final long serialVersionUID = 1L;
	private Font uhOhFont;
	
	
    public TextIconComboBoxRenederer() {
    	setOpaque(true);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
    }

    /*
     * This method finds the image and text corresponding
     * to the selected value and returns the label, set up
     * to display the text and image.
     */
    public Component getListCellRendererComponent( 
    									JList list,
                                       Object value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus) {
        
    	//Get the selected index. (The index param isn't
        //always valid, so just use the value.)
        //int selectedIndex = ((Integer)value).intValue();

    	FileSystemNode selectedItem = (FileSystemNode)value;
    	
        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }

        //Set the icon and text.  If icon was null, say so.
        Icon icon = selectedItem.getFileSystemRow().getIconLabel().getIcon();
        String label = selectedItem.getFileSystemRow().getIconLabel().getLabel();
        setIcon(icon);
        if (icon != null) {
            setText(label);
            setFont(list.getFont());
        } else {
            setUhOhText(label + " (no image available)",
                        list.getFont());
        }

        return this;
    }

    //Set the font and text when no image was found.
    protected void setUhOhText(String uhOhText, Font normalFont) {
        if (uhOhFont == null) { //lazily create this font
            uhOhFont = normalFont.deriveFont(Font.ITALIC);
        }
        setFont(uhOhFont);
        setText(uhOhText);
    }
}
